package client;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.jar.JarFile;

import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;

import pojo.SwingServerInformation;
import br.org.lh.ClientSwing.core.ClientSwingGenerator;

public class ClientHandler extends IoHandlerAdapter {

	public ClientHandler() {
		// TODO Auto-generated constructor stub
	}

	
	
	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		// TODO Auto-generated method stub
		super.exceptionCaught(session, cause);
		session.close();
		session.getCloseFuture().getSession().close();
	}



	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		// TODO Auto-generated method stub
		super.messageReceived(session, message);
		SwingServerInformation server = (SwingServerInformation) message;
		session.close();
		InputStream in = new ByteArrayInputStream (server.getFile());
		File f = new File (server.getJarName());
		OutputStream out = new FileOutputStream (f);
		byte[] buf = new byte[server.getFileSize()];
		int length;
		while ((length = in.read(buf)) > 0) {
			out.write(buf, 0, length);
		}
		JarFile jarFile = new JarFile (f);
		ClientSwingGenerator swing = new ClientSwingGenerator (jarFile,server.getAppLevelContext());
		swing.generateUI("Tela2.xml");
		System.out.print("ok");
		
	}
	
	

	
	
}
